package com.voice.call.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import voice.voice.call.cache.ConfigVosAccountCache;

import com.voice.call.common.Const;
import com.voice.call.entity.CallLog;
import com.voice.call.entity.VosAccount;
import com.voice.call.service.InviteVosBillService;
import com.voice.call.service.UserAccountService;
import com.voice.call.service.UserInfoService;
import com.voice.call.service.VosCallBackService;
import com.voice.call.utils.JSONUtil;
import com.voice.call.utils.StringUtil;

@Service
public class InviteVosBillServiceImpl implements InviteVosBillService{
	
	private static final Logger log = LoggerFactory.getLogger(InviteVosBillServiceImpl.class);
	
	@Resource
	private UserInfoService userInfoService;
	
	@Resource
	private ConfigVosAccountCache configVosAccountCache;
	
	@Resource
	private UserAccountService userAccountService;
	
	@Resource
	private VosCallBackService  vosCallBackService;

	@Override
	public String getStatus(){
		return "INVITE"; 
	}
	
	@Override
	public String getVosResponseText(String callInfo){
		
		
		
		 String[] res = callInfo.split("\n");
		
	 		if(res!=null && res.length>4){
	 			res[0]="SIP/2.0 300 Multiple Choices";
	 			List<String> list = new ArrayList<String>(Arrays.asList(res));
	 			//log.info("replay_remove");
	 			list.remove(4);
	 			//list.add(5, "Call-Info:remain-time=30");
	 			CallLog callLog = this.inviteToLog(list);
	 			if (callLog!=null && !StringUtil.isEmpty(callLog.getCalled())) {
	 				
	 				//log.info("callLog.getCalled()={}",callLog.getCalled());
	 				
	 				//判断帐号是否存在
		 			VosAccount vosAccount = configVosAccountCache.getVosAccountForPhonePrefix(callLog.getCalled());
		 			if (vosAccount!=null) {
		 				//log.info("icall 用户,客户端说:{}",callInfo);
		 				String remain_time = this.getRemainTime(vosAccount,callLog);
		 				log.info("caller:{},通话时长:{}",callLog.getCaller(),remain_time);
			 			if(remain_time!=null){
			 				list.add(5, remain_time);
			 			}
					}else {
						//log.info("vosAccount_is_null");
					}
				}
	 			String replay_msg = org.apache.commons.lang.StringUtils.join(list.toArray(),"\n");
	 			//log.info("replay_msg ="+replay_msg);
	 			return replay_msg;
	 			
	 		}
	 		
	 		String msg = "SIP/2.0 300 Multiple Choices\n"+callInfo;
	 		//log.info("replay_msg exception="+msg);
			return msg;
	}
	
	//判断是否为icall话单
	private boolean isCallInvite(CallLog callLog) {
		
	  	   VosAccount vosAccount = configVosAccountCache.getDefaultVosAccount();
	  	   if(vosAccount!=null){
	  		 if (callLog.getCallernum().startsWith(vosAccount.getVosPrefix())) {
				return true;
			 }
	  	   }
	  	   return false;
	}
	
	 private String getRemainTime(VosAccount vosAccount,CallLog callLog){
	  	   

	  	   
	  	   //VosAccount vosAccount = configVosAccountCache.getVosAccountStartWithPrefix(callLog.getCalled());
	  	   //VosAccount vosAccount = configVosAccountCache.getDefaultVosAccount();
	  	  

	  		if(vosAccount != null && !StringUtil.isEmpty(vosAccount.getPhonePrefix())){
	  			//log.info("getRemainTime 001");
	  			try {
	  				
	  				String leftTime = getVosCallLeftTime(vosAccount,callLog);	
		  			String remain_time = "Call-Info:remain-time="+leftTime;
		  			
		  			return remain_time;
					
				} catch (Exception e) {
					e.printStackTrace();
					log.info("获取分钟数发生异常");
					return "0";
				}
	  			
	  			
	  		}
	  		//log.info("getRemainTime");
	  		return "Call-Info:remain-time=0";
	  	   
	     }
	     
	     private CallLog inviteToLog(List<String> list){
	    	 
	    	 
	    	 try {
	    		 
	    		 String to = list.get(2);
	  	  	   String from = list.get(3);
	  	  	   String call_id_Str = list.get(4).replaceAll("Call-ID:", "").trim();
	  	  	   
	  	  	   CallLog callLog = new CallLog();
	  	  	   //主叫号码 caller
	  	  	   callLog.setCaller(this.getCallNumString(from));
	  	  	   //callLog.setCaller(from);
	  	  	   callLog.setCallernum(callLog.getCaller());
	  	  	   //被叫号码 called
	  	  	   callLog.setCalled(this.getCallNumString(to));
	  	  	   //callLog.setCalled(to);
	  	  	   //call_id
	  	  	   int index = call_id_Str.indexOf("@");
	  	  	   if(index!=-1){
	  	  		   call_id_Str = call_id_Str.substring(0, index);
	  	  	   }
	  	  	   callLog.setCallId(call_id_Str);
	  	  	   callLog.setCallType(0);
	  	  	   callLog.setEvent("callreq");
	  	  	   callLog.setLength(0);
	  	  	   callLog.setReason(0);
	  	  	   callLog.setSubreason(0);
	  	  	   callLog.setCallerBalance(0);
	  	  	   
	  	  	   return callLog;
				
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
	  	   
	  	  
	     }
	     
	     //获取手机号码
	     private String getCallNumString(String source){
	  	   
	  	    String regex = "(?<=\\<sip\\:)[^\\>]+";
	  		Pattern p = Pattern.compile(regex);//获取正则表达式中的分组，每一组小括号为一组
	  		Matcher m = p.matcher(source);//进行匹配
	  		if (m.find()) {//判断正则表达式是否匹配到
	  		    String pi = m.group(0);
	  		    int index = pi.indexOf("@");
	  		    if(index!=-1){
	  		    	return pi.substring(0, index);
	  		    	//return pi.substring(0, index).replaceAll("[a-zA-Z]+", "");
	  		    }
	  		    return  pi;
	  		    //return  pi.replaceAll("[a-zA-Z]+", "");
	  		}
	  		return null;
	  	   
	    }
	     //获取通话时长
	    private String getVosCallLeftTime(VosAccount vosAccount,CallLog callLog) {
	    	//log.info("getVosCallLeftTime 001");
	    	
	    	if (callLog!=null && vosAccount!=null && !StringUtil.isEmpty(callLog.getCalled()) && !StringUtil.isEmpty(callLog.getCallernum()) && !StringUtil.isEmpty(vosAccount.getPhonePrefix()) && !StringUtil.isEmpty(vosAccount.getVosPrefix())) {
	    		//log.info("getVosCallLeftTime 002");
	    		String called = callLog.getCalled().replaceAll("^"+vosAccount.getPhonePrefix(), "");//被叫号码
		    	String user_id=callLog.getCallernum().replaceAll("^"+vosAccount.getVosPrefix(), "");
		    	if (!StringUtil.isEmpty(vosAccount.getMcc()) && vosAccount.getMcc().equals(Const.VOS_DEFAULT)) {
		    		//log.info("getVosCallLeftTime 003");
		    		//1.获取通话时长
					log.info("电话拨打,需要设置最大通话时长!");
					//leftTime = userAccountService.getCallLeftTime(callLog.getCallernum(), called);
					return userAccountService.getCallLeftTimeForUserId(user_id, called);
					
				}else { //第三方
					//log.info("getVosCallLeftTime 004");
					if (!StringUtil.isEmpty(vosAccount.getLefttimeCallback())) {
						return vosCallBackService.getLeftTime(vosAccount.getLefttimeCallback(),user_id, callLog.getCaller(), called);
					}
					log.info("第三方话单未配置回调地址!");
					return "0";
				}
			}
	    	//log.info("getVosCallLeftTime 005");
	    	return "0";
	    	
	    	
		}
}
